"""
数据库连接管理模块
用于从MySQL数据库获取视频流信息
"""

import logging
import pymysql
from typing import List, Dict, Any, Optional
import json
import ast

# 配置日志
logger = logging.getLogger(__name__)

class DBManager:
    """数据库管理器，用于连接MySQL并获取视频流信息"""
    
    def __init__(self, host="localhost", port=3306, user="root", 
                 password="a361154", database="xygk-factory-safe-v1"):
        """
        初始化数据库连接
        
        Args:
            host: 数据库主机名
            port: 数据库端口
            user: 数据库用户名
            password: 数据库密码
            database: 数据库名称
        """
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.database = database
        self.connection = None
        self.cursor = None
        
        # 尝试连接数据库
        self.connect()
        
    def connect(self) -> bool:
        """
        连接到数据库
        
        Returns:
            连接是否成功
        """
        try:
            self.connection = pymysql.connect(
                host=self.host,
                port=self.port,
                user=self.user,
                password=self.password,
                database=self.database,
                charset='utf8mb4',
                cursorclass=pymysql.cursors.DictCursor
            )
            self.cursor = self.connection.cursor()
            logger.info(f"成功连接到数据库 {self.database}")
            return True
        except Exception as e:
            logger.error(f"连接数据库失败: {e}")
            return False
    
    def disconnect(self):
        """断开数据库连接"""
        if self.cursor:
            self.cursor.close()
        if self.connection:
            self.connection.close()
        logger.info("数据库连接已断开")
    
    def reconnect_if_needed(self):
        """如果连接断开，重新连接"""
        try:
            if self.connection and self.connection.open:
                # 尝试执行一个简单的查询来测试连接
                self.cursor.execute("SELECT 1")
                return True
            else:
                logger.info("数据库连接已断开，尝试重新连接")
                return self.connect()
        except Exception as e:
            logger.warning(f"检查数据库连接时出错: {e}")
            return self.connect()
    
    def get_video_streams(self) -> List[Dict[str, Any]]:
        """
        获取所有视频流信息
        
        Returns:
            视频流信息列表
        """
        if not self.reconnect_if_needed():
            logger.error("无法连接到数据库，无法获取视频流信息")
            return []
        
        try:
            query = """
            SELECT 
                id, camera_id, rtsp_address, line_direction, name
            FROM 
                safe_video_stream_info
            WHERE 
                deleted = 0
            """
            self.cursor.execute(query)
            streams = self.cursor.fetchall()
            
            # 处理line_direction字段，将字符串转换为列表
            for stream in streams:
                if stream.get('line_direction'):
                    try:
                        # 尝试使用ast.literal_eval安全地解析字符串为Python对象
                        line_direction = ast.literal_eval(stream['line_direction'])
                        stream['line_direction'] = line_direction
                    except (SyntaxError, ValueError) as e:
                        logger.warning(f"解析line_direction失败: {e}, 原始值: {stream['line_direction']}")
                        # 如果解析失败，设置默认值
                        stream['line_direction'] = [[150, 100], [1100, 100], [1100, 650], [150, 650]]
                else:
                    # 如果line_direction为空，设置默认值
                    stream['line_direction'] = [[150, 100], [1100, 100], [1100, 650], [150, 650]]
            
            logger.info(f"成功获取 {len(streams)} 个视频流信息")
            return streams
        except Exception as e:
            logger.error(f"获取视频流信息失败: {e}")
            return []
    
    def get_video_stream_by_id(self, stream_id: int) -> Optional[Dict[str, Any]]:
        """
        根据ID获取单个视频流信息
        
        Args:
            stream_id: 视频流ID
            
        Returns:
            视频流信息或None
        """
        if not self.reconnect_if_needed():
            logger.error("无法连接到数据库，无法获取视频流信息")
            return None
        
        try:
            query = """
            SELECT 
                id, camera_id, rtsp_address, line_direction, name
            FROM 
                safe_video_stream_info
            WHERE 
                id = %s AND deleted = 0
            """
            self.cursor.execute(query, (stream_id,))
            stream = self.cursor.fetchone()
            
            if stream and stream.get('line_direction'):
                try:
                    # 尝试使用ast.literal_eval安全地解析字符串为Python对象
                    line_direction = ast.literal_eval(stream['line_direction'])
                    stream['line_direction'] = line_direction
                except (SyntaxError, ValueError) as e:
                    logger.warning(f"解析line_direction失败: {e}, 原始值: {stream['line_direction']}")
                    # 如果解析失败，设置默认值
                    stream['line_direction'] = [[150, 100], [1100, 100], [1100, 650], [150, 650]]
            elif stream:
                # 如果line_direction为空，设置默认值
                stream['line_direction'] = [[150, 100], [1100, 100], [1100, 650], [150, 650]]
            
            return stream
        except Exception as e:
            logger.error(f"获取视频流信息失败: {e}")
            return None
    
    def update_stream_status(self, stream_id: int, status: int) -> bool:
        """
        更新视频流状态
        
        Args:
            stream_id: 视频流ID
            status: 状态值 (0: 禁用, 1: 启用)
            
        Returns:
            更新是否成功
        """
        if not self.reconnect_if_needed():
            logger.error("无法连接到数据库，无法更新视频流状态")
            return False
        
        try:
            query = """
            UPDATE safe_video_stream_info
            SET status = %s
            WHERE id = %s
            """
            self.cursor.execute(query, (status, stream_id))
            self.connection.commit()
            logger.info(f"成功更新视频流状态，ID={stream_id}, 状态={status}")
            return True
        except Exception as e:
            logger.error(f"更新视频流状态失败: {e}")
            self.connection.rollback()
            return False
    
    def __del__(self):
        """析构函数，确保断开连接"""
        self.disconnect()


if __name__ == "__main__":
    # 配置日志
    logging.basicConfig(level=logging.INFO)
    
    # 测试数据库连接
    db = DBManager()
    streams = db.get_video_streams()
    
    for stream in streams:
        print(f"ID: {stream['id']}, 摄像头ID: {stream['camera_id']}, RTSP地址: {stream['rtsp_address']}")
        print(f"线条方向: {stream['line_direction']}")
        print("-" * 50)